<!-- 使用组件<comment-section /> -->
<template>
  <view class="comment-section">
    <scroll-view scroll-y="true" class="comment-list" :style="{ height: scrollHeight + 'px' }">
      <up-list @scrolltolower="bottoming">
        <view v-for="(comment, index) in comments" :key="index" class="comment-item">
          <view class="comment-header">
            <span class="comment-user">
              <!-- <image style="width: 1.8rem;height: 1.8rem;border-radius: 50%;vertical-align: middle;"
              src="https://img2.baidu.com/it/u=2287614273,1325409419&fm=253&fmt=auto&app=138&f=JPEG?w=809&h=800">
            </image> -->
              <image style="width: 1.8rem;height: 1.8rem;border-radius: 50%;vertical-align: middle;"
                :src="comment.avatar_sign">
              </image>
              <span>{{ comment.user_name }}
                <image v-if="comment.user_name == userName && comment.user_code == userCode"
                  style="width: 1.4rem;height: 0.8rem;margin-left: 10rpx;" src="/static/images/zz.png"></image>
              </span>
            </span>
            <!-- <span class="comment-time">{{ formatTime(comment.time) }}</span> -->
            <span class="comment-time">{{ comment.add_time_str }}</span>
          </view>
          <view class="comment-content" @click="prepareReply(index, null, comment)">{{ comment.content }}</view>
          <view class="comment-actions" @click="prepareReply(index, null, comment)">
            <span class="action-btn">
              <span class="dleCommentBtn" style="color: red;margin-right: 30rpx;"
                v-if="comment.user_name == userName && comment.user_code == userCode"
                @click.stop="handDleComment($event, comment)">删除</span>
              <!-- {{ comment.likes || 0 }} {{ comment.isLiked ? '取消点赞' : '点赞' }} -->
              <image :src="comment.isLiked ? '/static/images/xinxin2.png' : '/static/images/xinxin.png'" style=" width: 35rpx;
    height: 35rpx;margin-right: 8rpx;" @click.stop="toggleLike(index, $event)">
              </image>
              <span @click.stop="toggleLike(index, $event)">{{ formatToWan(comment.likes) }}</span>
              <image class="disListCss" @click.stop="toggleDisLike(index, $event)"
                :src="comment.disLiked ? '/static/images/cai2.png' : '/static/images/cai.png'" style=" width: 35rpx;
    height: 35rpx;margin-left: 20rpx;">
              </image>
            </span>
            <span class="action-btn">回复</span>
          </view>

          <!-- 回复列表（平铺显示） -->
          <view v-if="comment.children" class="replies-container">
            <view v-for="(reply, replyIndex) in visibleReplies(comment.children)" :key="reply.id || replyIndex"
              class="reply-item">
              <view class="reply-header">
                <span class="reply-user">
                  <!-- <image style="width: 1.8rem;height: 1.8rem;border-radius: 50%;vertical-align: middle;"
                  src="https://img2.baidu.com/it/u=2287614273,1325409419&fm=253&fmt=auto&app=138&f=JPEG?w=809&h=800">
                </image> -->
                  <image style="width: 1.8rem;height: 1.8rem;border-radius: 50%;vertical-align: middle;"
                    :src="reply.avatar_sign">
                  </image>
                  {{ reply.user_name }}
                  <image v-if="comment.user_name == userName && comment.user_code == userCode"
                    style="width: 1.4rem;height: 0.8rem;margin-left: 10rpx;" src="/static/images/zz.png"></image>
                </span>
                <text class="reply-to" v-if="reply.parent_name">回复 @{{ reply.parent_name }}</text>
                <!-- <span class="reply-time">{{ formatTime(reply.time) }}</span> -->
                <span class="reply-time">{{ reply.add_time_str }}</span>
              </view>
              <view class="reply-content" @click="prepareReply(index, reply, comment)">{{ reply.content }}</view>
              <view class="reply-actions" @click="prepareReply(index, reply, comment)">
                <span class="action-btn">
                  <span class="dleCommentBtn" style="color: red;margin-right: 30rpx;"
                    v-if="reply.user_name == userName && reply.user_code == userCode"
                    @click.stop="handDleComment($event, reply)">删除</span>
                  <image :src="reply.isLiked ? '/static/images/xinxin2.png' : '/static/images/xinxin.png'" style=" width: 35rpx;
    height: 35rpx;margin-right: 8rpx;" @click.stop="itemToggleLike(reply, replyIndex, $event)">
                  </image>
                  <span @click.stop="itemToggleLike(reply, replyIndex, $event)">{{ formatToWan(reply.likes) }}</span>
                  <image class="disListCss" @click.stop="itemToggleDisLike(reply, replyIndex, $event)"
                    :src="reply.disLiked ? '/static/images/cai2.png' : '/static/images/cai.png'" style=" width: 35rpx;
    height: 35rpx;margin-left: 20rpx;">
                  </image>
                </span>
                <span class="action-btn" style="margin-left: 26rpx;">回复</span>
              </view>
            </view>

            <!-- 展开/收起按钮 -->
            <view v-if="comment.children.length > 2" class="expand-btn" @click="toggleReplies(index)">
              -----{{ comment.expanded ? '收起回复' : `查看全部${comment.children.length}条回复` }}-----
            </view>
          </view>
        </view>
      </up-list>
    </scroll-view>

    <view class="comment-input">
      <input v-model="inputContent" ref="inputRef" class="input" :focus="isFocus" :cursor-spacing="10"
        :placeholder="replyToInfo.replyToIndex === -1 ? '发表评论' : `回复 @${comments[replyToInfo.replyToIndex]?.user_name}${replyToInfo.replyToReply ? '@' + replyToInfo.replyToReply.user_name : ''}`"
        @confirm="submitContent" @focus="isFocus = true" @blur="blur" />
      <button @click="submitContent" class="submit-btn" :loading="btnLoading">发送</button>
    </view>
  </view>
  <upModal :modalShow="modalShow" :modalText1="'是否删除该评论?'" :showImage="false" :isCancel="true"
    @cancel="modalShow = false" @cloos="cloos"></upModal>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { setComment, commentDel } from '@/api/article/article.js'
import upModal from '@/components/upModal.vue';
import { formatToWan } from '@/utils/numericalToW'
const props = defineProps({
  commentData: {// 评论数据
    type: Array,
    default: () => [],
  },
  funplayCode: {
    type: String,
    default: '',
  }
})
const btnLoading = ref(false)
const modalShow = ref(false)
// 当前登录用户的信息
const userId = ref(uni.getStorageSync('dplID'))
const userCode = ref(uni.getStorageSync('userCode'))
const userName = ref(uni.getStorageSync('username'))
const avatarSrc = ref(uni.getStorageSync('avatarUrl'))
// 评论数据
let comments = ref(props.commentData)
// 监听 props.commentData 的变化
watch(() => props.commentData, (newValue) => {
  comments.value = newValue
}, { deep: true })
// let comments = ref([
//   {
//     username: '用户1',
//     content: '这是一个测试评论哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
//     time: new Date().getTime() - 3600000,
//     likes: 5,
//     isLiked: false,
//     disLiked: false,
//     expanded: false,
//     children: [
//       {
//         username: '用户2',
//         toUser: '用户1',
//         content: '这是对测试评论的回复1哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
//         time: new Date().getTime() - 1800000,
//         likes: 4,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//         children: [
//           {
//             username: '用户2',
//             toUser: '用户1',
//             content: '这是对测试评论的回复2',
//             time: new Date().getTime() - 1800000,
//             likes: 4,
//             isLiked: false,
//             disLiked: false,
//             expanded: false,
//             children: [
//               {
//                 username: '用户2',
//                 toUser: '用户1',
//                 content: '这是对测试评论的回复3',
//                 time: new Date().getTime() - 1800000,
//                 likes: 4,
//                 isLiked: false,
//                 disLiked: false,
//                 expanded: false,
//                 children: [
//                   {
//                     username: '用户2',
//                     toUser: '用户1',
//                     content: '这是对测试评论的回复4',
//                     time: new Date().getTime() - 1800000,
//                     likes: 4,
//                     isLiked: false,
//                     disLiked: false,
//                     expanded: false,
//                   },
//                 ]
//               },
//             ]
//           },
//         ]
//       },
//       {
//         username: '用户3',
//         toUser: '用户1',
//         content: '这是对测试评论的回复2',
//         time: new Date().getTime() - 900000,
//         likes: 3,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//       },
//       {
//         username: '用户4',
//         toUser: '用户1',
//         content: '这是对测试评论的回复3',
//         time: new Date().getTime() - 360000,
//         likes: 2,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//       },
//       {
//         username: '用户5',
//         toUser: '用户1',
//         content: '这是对测试评论的回复4',
//         time: new Date().getTime() - 180000,
//         likes: 1,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//       }
//     ]
//   },
//   {
//     username: '用户1',
//     content: '这是一个测试评论哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
//     time: new Date().getTime() - 3600000,
//     likes: 5,
//     isLiked: false,
//     disLiked: false,
//     expanded: false,
//     children: [
//       {
//         username: '用户2111',
//         toUser: '用户1',
//         content: '这是对测试评论的回复1哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
//         time: new Date().getTime() - 1800000,
//         likes: 4,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//         children: [
//           {
//             username: '用户66662',
//             toUser: '用户1',
//             content: '这是对测试评论的回复2',
//             time: new Date().getTime() - 1800000,
//             likes: 4,
//             isLiked: false,
//             disLiked: false,
//             expanded: false,
//             children: [
//               {
//                 username: '用户27777',
//                 toUser: '用户1',
//                 content: '这是对测试评论的回复3',
//                 time: new Date().getTime() - 1800000,
//                 likes: 4,
//                 isLiked: false,
//                 disLiked: false,
//                 expanded: false,
//                 children: [
//                   {
//                     username: '用户66662',
//                     toUser: '用户1',
//                     content: '这是对测试评论的回复4',
//                     time: new Date().getTime() - 1800000,
//                     likes: 4,
//                     isLiked: false,
//                     disLiked: false,
//                     expanded: false,
//                   },
//                 ]
//               },
//             ]
//           },
//         ]
//       },
//       {
//         username: '用户57777',
//         toUser: '用户1',
//         content: '这是对测试评论的回复4',
//         time: new Date().getTime() - 180000,
//         likes: 1,
//         isLiked: false,
//         disLiked: false,
//         expanded: false,
//       }
//     ]
//   },
// ])
// 处理评论数据结构
function flattenChildren(arr) {
  let result = [];
  for (let item of arr) {
    result.push(item);
    if (item.children && item.children.length > 0) {
      result = result.concat(flattenChildren(item.children));
      // 清空当前的 children 数组，因为我们要把所有孩子都提升到第一层
      item.children = [];
    }
  }
  return result;
}
comments.value = comments.value.map(item => {
  return {
    ...item,
    children: flattenChildren(item.children)
  };
});
let isFocus = ref(false)
// 输入框内容
const inputContent = ref('')
// 当前正在回复的评论索引和回复对象
const replyToInfo = ref({
  replyToIndex: -1,  // 评论索引
  replyToReply: null // 回复对象（如果是回复回复）
})
// 输入框引用
const inputRef = ref(null)
// 滚动区域高度
const scrollHeight = ref(500)
const emit = defineEmits(['scrollToComment', 'commentListPages'])
let commentItemData = ref({})
const respondent = ref('')// 被回复人
// 准备回复
const prepareReply = (index, reply, comment) => {
  respondent.value = comment.user_name
  commentItemData.value = comment
  // emit('scrollToComment')
  isFocus.value = true
  replyToInfo.value = {
    replyToIndex: index,
    replyToReply: reply || null
  }
  inputContent.value = ''
}
const bottoming = () => {// 上拉触底事件
  // console.log('上拉触底事件');
  emit('commentListPages')
}
const replyToReplyData = ref('')// 被回复的评论人
// 提交内容（评论或回复）
const submitContent = () => {
  btnLoading.value = true
  // console.log('提交内容', inputContent.value.trim());
  if (!inputContent.value.trim()) {
    uni.showToast({
      title: '内容不能为空',
      icon: 'none'
    })
    return
  }
  let para = {
    funpaly_code: props.funplayCode,
    user_code: userCode.value,
    parent_code: commentItemData.value.comment_code == '1f' ? '0' : commentItemData.value.comment_code,
    content: inputContent.value,
  }
  setComment(para).then((res) => {
    if (res.code == 200) {
      // getComment()
      const { replyToIndex, replyToReply } = replyToInfo.value
      replyToReplyData.value = replyToReply?.user_name
      if (replyToIndex === -1) {
        // 提交新评论
        const comment = {
          user_name: userName.value,
          user_code: userCode.value,
          content: inputContent.value.trim(),
          add_time_str: formatTime(new Date()),
          likes: 0,
          isLiked: false,
          expanded: false,
          children: [],
          avatar_sign: avatarSrc.value,
        }
        comments.value.unshift(comment)
      } else {
        const baseReply = {
          user_name: userName.value,
          user_code: userCode.value,
          content: inputContent.value.trim(),
          add_time_str: formatTime(new Date()),
          avatar_sign: avatarSrc.value,
        }
        // const reply = replyToReply
        //   ? { ...baseReply, parent_name: replyToReply.user_name }
        //   : { ...baseReply, parent_name: comments.value[replyToIndex].user_name }
        const reply = respondent.value ? { ...baseReply, parent_name: respondent.value } : { ...baseReply, parent_name: comments.value[replyToIndex].user_name }
        // 添加唯一ID
        reply.id = Date.now() + Math.random().toString(36).substr(2, 9)

        if (!comments.value[replyToIndex].children) {
          comments.value[replyToIndex].children = []
        }

        // 如果是回复回复，找到原始回复并添加
        if (replyToReply) {
          comments.value[replyToIndex].children.unshift(reply)
        } else {
          // 如果是直接回复评论，可以添加到开头或结尾
          comments.value[replyToIndex].children.unshift(reply)
        }
      }
    } else {
      uni.showToast({
        title: `错误!${res.msg}`,
        icon: 'none',
        duration: 2000
      })
    }
  }).finally(() => {
    // 重置状态
    btnLoading.value = false
    inputContent.value = ''
    replyToInfo.value = { replyToIndex: -1, replyToReply: null }
  })
}
let delPara = ref({})
const handDleComment = (event, item) => {// 评论删除
  event.stopPropagation(); // 阻止事件冒泡
  // console.log('item', item);
  delPara.value = {
    usercode: item.user_code,
    commentcode: item.comment_code,
  }
  modalShow.value = true
}
const cloos = () => {
  commentDel(delPara.value).then((res) => {
    if (res.code == 200) {
      uni.showToast({
        title: '删除成功',
        icon: "success",
        duration: 2000
      })
    } else {
      uni.showToast({
        title: `删除失败!${res.msg}`,
        icon: "none",
        duration: 2000
      })
    }
  }).catch((err) => {
    uni.showToast({
      title: `删除失败!${err.msg}`,
      icon: "none",
      duration: 2000
    })
  }).finally(() => {
    modalShow.value = false
  })
}
// 点赞/取消点赞
const toggleLike = (index, event) => {
  event.stopPropagation(); // 阻止事件冒泡
  if (comments.value[index].isLiked) {
    comments.value[index].likes--
  } else {
    comments.value[index].likes++
  }
  comments.value[index].isLiked = !comments.value[index].isLiked
}
// 点踩
const toggleDisLike = (index, event) => {
  event.stopPropagation(); // 阻止事件冒泡
  // if (comments.value[index].disLiked) {
  //   comments.value[index].likes--
  // } else {
  //   comments.value[index].likes++
  // }
  comments.value[index].disLiked = !comments.value[index].disLiked
}
// 子项的点赞/取消点赞
const itemToggleLike = (row, index, event) => {
  event.stopPropagation(); // 阻止事件冒泡
  // console.log(row, index);
  if (row.isLiked) {
    row.likes--
  } else {
    row.likes++
  }
  row.isLiked = !row.isLiked
}
// 子项的点踩
const itemToggleDisLike = (row, index, event) => {
  event.stopPropagation(); // 阻止事件冒泡
  // console.log(row, index);
  // if (row.isLiked) {
  //   row.likes--
  // } else {
  //   row.likes++
  // }
  row.disLiked = !row.disLiked
}
// 切换回复的展开/收起状态
const toggleReplies = (index) => {
  comments.value[index].expanded = !comments.value[index].expanded
}

// 获取可见的回复（默认显示2条）
const visibleReplies = (children) => {
  const commentIndex = comments.value.findIndex(c => c.children === children)
  if (!comments.value[commentIndex].expanded) {
    return children.slice(0, 2)
  }
  return children
}
const blur = () => {// 失去焦点
  // 重置状态
  isFocus.value = false
  // 延迟1秒后执行
  setTimeout(() => {
    // inputContent.value = ''
    replyToInfo.value = { replyToIndex: -1, replyToReply: null }
  }, 10)
}
// 时间格式化
const formatTime = (timestamp) => {
  // const date = new Date(timestamp)
  // const now = new Date()
  // const diff = now.getTime() - timestamp

  // if (diff < 86400000) { // 1天内
  //   return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
  // } else if (diff < 2592000000) { // 30天内
  //   return `${date.getMonth() + 1}-${date.getDate()}`
  // } else {
  //   return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  // }
  const data = new Date(timestamp);
  const month = data.getMonth() + 1;
  const day = data.getDate();
  const year = data.getFullYear();
  const hours = data.getHours();
  const minutes = data.getMinutes();
  const seconds = data.getSeconds();
  const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return formattedTime;
}
// 计算滚动区域高度
onMounted(() => {
  uni.getSystemInfo({
    success: (res) => {
      const query = uni.createSelectorQuery().in(this)
      query.select('.comment-input').boundingClientRect(data => {
        scrollHeight.value = res.windowHeight - data.height - 20
      }).exec()
    }
  })
})
</script>

<style scoped>
/* 原有样式保持不变 */
.comment-section {
  height: 76vh;
  /* padding: 20rpx; */
  background-color: #f5f5f5;
  overflow-y: auto;
}

.comment-list {
  margin-bottom: 20rpx;
}

.comment-item {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.comment-user {
  font-weight: bold;
  color: #333;

  image {
    width: 1.8rem;
    height: 1.8rem;
    border-radius: 50%;
    vertical-align: middle;
  }
}

.comment-time {
  color: #999;
  font-size: 24rpx;
}

.comment-content {
  width: 96%;
  max-height: 2.4rem;
  color: #666;
  font-size: 24rpx;
  line-height: 1.5;
  margin-bottom: 15rpx;
  margin-left: 4%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 30rpx;
}

.action-btn {
  color: #007aff;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  image {
    width: 35rpx;
    height: 35rpx;
    margin-right: 10rpx;
  }

  .disListCss {
    margin-left: 30rpx;
  }

  .dleCommentBtn {
    color: red;
    margin-right: 30rpx;
  }
}

/* 回复列表样式 */
.replies-container {
  margin-top: 20rpx;
  padding-left: 40rpx;
  border-left: 2rpx solid #eee;
}

.reply-item {
  background-color: #f9f9f9;
  padding: 15rpx;
  margin-bottom: 15rpx;
  border-radius: 8rpx;
  position: relative;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
  font-size: 24rpx;
}

.reply-user {
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;

  image {
    width: 1.8rem;
    height: 1.8rem;
    border-radius: 50%;
    vertical-align: middle;
  }
}

.reply-time {
  color: #999;
  margin-right: 10rpx;
  position: absolute;
  right: 0;
}

.reply-to {
  max-width: 7rem;
  color: #007aff;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏溢出内容 */
  text-overflow: ellipsis;
  /* 显示省略号 */
}

.reply-content {
  width: 96%;
  max-height: 2.4rem;
  color: #666;
  line-height: 1.4;
  font-size: 24rpx;
  margin-left: 4%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.reply-actions {
  margin-top: 8rpx;
  display: flex;
  justify-content: flex-end;
}

.expand-btn {
  color: #007aff;
  font-size: 24rpx;
  text-align: center;
  padding: 10rpx 0;
  margin-top: 10rpx;
}

.comment-input {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 18rpx 10rpx;
  border-radius: 10rpx;
  position: sticky;
  bottom: 0;
}

.input {
  flex: 1;
  height: 60rpx;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.submit-btn {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #EAB3B8;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style>